#include "../inc/st7735_spi_dma.h"
#include "definitions.h"
#include "../inc/st7735.h"

#define SWAP_UINT16_BYTES(x) ((((x) >> 8) & 0xFF) | (((x) & 0xFF) << 8))

volatile uint8_t gDma0IdleFlag = 1;

void ST7735_SPI_DMA_Callback(DMAC_TRANSFER_EVENT event, uintptr_t context);

void ST7735_SPI_DMA_Init(void)
{
    // SERCOM1_SPI_Initialize();
    DMAC_ChannelCallbackRegister(DMAC_CHANNEL_0, ST7735_SPI_DMA_Callback, 0);
}

void ST7735_SPI_DMA_Transfer(const void *buffer, size_t size)
{
    const uint8_t *colorBuffer = (const uint8_t *)buffer;
    static uint8_t tempBuffer[ST7735_WIDTH * ST7735_HEIGHT * 2];
    memcpy(tempBuffer, colorBuffer, size);

    LCD_DC_Set();

    SERCOM1_SPI_Write(&tempBuffer[0], 1);
    if (size > 1)
    {
        volatile uint32_t *spiDataReg = &SERCOM1_REGS->SPIM.SERCOM_DATA;
        DMAC_ChannelTransfer(DMAC_CHANNEL_0, &tempBuffer[1], (const void *)spiDataReg, size - 1);
        gDma0IdleFlag = 0;
    }

    // SERCOM1_SPI_Write(&tempBuffer[0], size);
}

uint8_t ST7735_SPI_DMA_IsIdle(void) { return gDma0IdleFlag; }

void ST7735_SPI_DMA_Callback(DMAC_TRANSFER_EVENT event, uintptr_t context) { gDma0IdleFlag = 1; }
